// DOM元素
document.addEventListener('DOMContentLoaded', () => {
    // 主要DOM元素
    const mainColor = document.getElementById('mainColor');
    const mainColorHex = document.getElementById('mainColorHex');
    const mainColorPreview = document.getElementById('mainColorPreview');
    const schemeButtons = document.querySelectorAll('.scheme-btn');
    const addCustomColorBtn = document.getElementById('addCustomColor');
    const customColorsContainer = document.getElementById('customColorsContainer');
    const generateBtn = document.getElementById('generateBtn');
    const resultsSection = document.getElementById('resultsSection');
    const generatedPalette = document.getElementById('generatedPalette');
    const harmonyScore = document.getElementById('harmonyScore');
    const harmonyScoreBar = document.getElementById('harmonyScoreBar');
    const paletteDetails = document.getElementById('paletteDetails');
    const saveBtn = document.getElementById('saveBtn');
    const copyBtn = document.getElementById('copyBtn');
    const savedPalettesContainer = document.getElementById('savedPalettesContainer');

    // 当前选中的配色方案
    let currentScheme = 'complementary';
    
    // 初始化
    initColorPickers();
    loadSavedPalettes();
    
    // 事件监听器
    mainColor.addEventListener('input', updateMainColor);
    mainColorHex.addEventListener('input', updateMainColorFromHex);
    
    schemeButtons.forEach(button => {
        button.addEventListener('click', () => {
            schemeButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            currentScheme = button.dataset.scheme;
        });
    });
    
    addCustomColorBtn.addEventListener('click', addCustomColor);
    generateBtn.addEventListener('click', generatePalette);
    saveBtn.addEventListener('click', savePalette);
    copyBtn.addEventListener('click', copyPaletteCode);
    
    // 初始化颜色选择器
    function initColorPickers() {
        // 设置主颜色选择器的事件
        setupColorPicker(mainColor, mainColorHex, mainColorPreview);
        
        // 设置初始自定义颜色的事件
        const customColors = document.querySelectorAll('.customColor');
        const customColorHexes = document.querySelectorAll('.customColorHex');
        const customPreviews = document.querySelectorAll('.custom-preview');
        const removeButtons = document.querySelectorAll('.remove-btn');
        
        customColors.forEach((color, index) => {
            setupColorPicker(color, customColorHexes[index], customPreviews[index]);
            if (removeButtons[index]) {
                removeButtons[index].addEventListener('click', function() {
                    this.closest('.custom-color-item').remove();
                });
            }
        });
    }
    
    // 设置颜色选择器的事件
    function setupColorPicker(colorInput, hexInput, preview) {
        colorInput.addEventListener('input', () => {
            hexInput.value = colorInput.value;
            preview.style.backgroundColor = colorInput.value;
        });
        
        hexInput.addEventListener('input', () => {
            // 验证十六进制颜色格式
            const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
            if (hexRegex.test(hexInput.value)) {
                colorInput.value = hexInput.value;
                preview.style.backgroundColor = hexInput.value;
            }
        });
    }
    
    // 更新主颜色
    function updateMainColor() {
        mainColorHex.value = mainColor.value;
        mainColorPreview.style.backgroundColor = mainColor.value;
    }
    
    // 从十六进制输入更新主颜色
    function updateMainColorFromHex() {
        const hexRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
        if (hexRegex.test(mainColorHex.value)) {
            mainColor.value = mainColorHex.value;
            mainColorPreview.style.backgroundColor = mainColorHex.value;
        }
    }
    
    // 添加自定义颜色
    function addCustomColor() {
        const customColorItem = document.createElement('div');
        customColorItem.className = 'custom-color-item';
        
        // 生成一个随机颜色
        const randomColor = getRandomColor();
        
        customColorItem.innerHTML = `
            <div class="color-picker-container">
                <input type="color" class="customColor" value="${randomColor}">
                <input type="text" class="customColorHex" value="${randomColor}">
            </div>
            <div class="color-preview custom-preview" style="background-color: ${randomColor};"></div>
            <button class="remove-btn"><i class="fas fa-times"></i></button>
        `;
        
        customColorsContainer.appendChild(customColorItem);
        
        // 设置新添加的颜色选择器的事件
        const newColorInput = customColorItem.querySelector('.customColor');
        const newHexInput = customColorItem.querySelector('.customColorHex');
        const newPreview = customColorItem.querySelector('.custom-preview');
        const removeBtn = customColorItem.querySelector('.remove-btn');
        
        setupColorPicker(newColorInput, newHexInput, newPreview);
        
        removeBtn.addEventListener('click', function() {
            customColorItem.remove();
        });
        
        // 添加动画效果
        customColorItem.style.opacity = '0';
        setTimeout(() => {
            customColorItem.style.opacity = '1';
        }, 10);
    }
    
    // 生成随机颜色
    function getRandomColor() {
        const letters = '0123456789ABCDEF';
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    
    // 生成配色方案
    function generatePalette() {
        // 显示加载动画
        generateBtn.innerHTML = '<span class="loading"></span> 生成中...';
        generateBtn.disabled = true;
        
        // 延迟执行以显示加载动画
        setTimeout(() => {
            // 获取主颜色
            const baseColor = mainColor.value;
            
            // 获取所有自定义颜色
            const customColorInputs = document.querySelectorAll('.customColor');
            const customColors = Array.from(customColorInputs).map(input => input.value);
            
            // 根据选择的方案生成配色
            let generatedColors = [];
            
            // 添加主颜色和自定义颜色
            generatedColors.push(baseColor);
            generatedColors = generatedColors.concat(customColors);
            
            // 根据选择的方案添加额外的颜色
            const additionalColors = generateAdditionalColors(baseColor, currentScheme, customColors);
            generatedColors = generatedColors.concat(additionalColors);
            
            // 确保颜色不重复
            generatedColors = [...new Set(generatedColors)];
            
            // 计算和谐度评分
            const score = calculateHarmonyScore(generatedColors);
            
            // 显示结果
            displayResults(generatedColors, score);
            
            // 恢复按钮状态
            generateBtn.innerHTML = '生成配色方案';
            generateBtn.disabled = false;
            
            // 激活结果区域
            resultsSection.classList.add('active');
            
            // 平滑滚动到结果区域
            resultsSection.scrollIntoView({ behavior: 'smooth' });
        }, 800); // 800ms的延迟以显示加载动画
    }
    
    // 生成额外的颜色
    function generateAdditionalColors(baseColor, scheme, customColors) {
        const hslBase = hexToHSL(baseColor);
        const additionalColors = [];
        
        switch(scheme) {
            case 'complementary':
                // 互补色
                additionalColors.push(hslToHex((hslBase.h + 180) % 360, hslBase.s, hslBase.l));
                break;
                
            case 'analogous':
                // 类似色 (相邻的颜色)
                additionalColors.push(hslToHex((hslBase.h + 30) % 360, hslBase.s, hslBase.l));
                additionalColors.push(hslToHex((hslBase.h + 60) % 360, hslBase.s, hslBase.l));
                additionalColors.push(hslToHex((hslBase.h - 30 + 360) % 360, hslBase.s, hslBase.l));
                break;
                
            case 'triadic':
                // 三角色 (相隔120度的颜色)
                additionalColors.push(hslToHex((hslBase.h + 120) % 360, hslBase.s, hslBase.l));
                additionalColors.push(hslToHex((hslBase.h + 240) % 360, hslBase.s, hslBase.l));
                break;
                
            case 'split-complementary':
                // 分裂互补色
                additionalColors.push(hslToHex((hslBase.h + 150) % 360, hslBase.s, hslBase.l));
                additionalColors.push(hslToHex((hslBase.h + 210) % 360, hslBase.s, hslBase.l));
                break;
                
            case 'tetradic':
                // 四角色 (矩形)
                additionalColors.push(hslToHex((hslBase.h + 90) % 360, hslBase.s, hslBase.l));
                additionalColors.push(hslToHex((hslBase.h + 180) % 360, hslBase.s, hslBase.l));
                additionalColors.push(hslToHex((hslBase.h + 270) % 360, hslBase.s, hslBase.l));
                break;
                
            case 'monochromatic':
                // 单色调 (相同色相，不同亮度和饱和度)
                additionalColors.push(hslToHex(hslBase.h, Math.min(hslBase.s + 20, 100), hslBase.l));
                additionalColors.push(hslToHex(hslBase.h, Math.max(hslBase.s - 20, 0), hslBase.l));
                additionalColors.push(hslToHex(hslBase.h, hslBase.s, Math.min(hslBase.l + 20, 100)));
                additionalColors.push(hslToHex(hslBase.h, hslBase.s, Math.max(hslBase.l - 20, 0)));
                break;
        }
        
        // 如果用户提供了自定义颜色，尝试生成与之和谐的颜色
        if (customColors.length > 0) {
            customColors.forEach(color => {
                const hslCustom = hexToHSL(color);
                // 添加一个与自定义颜色相关的颜色
                additionalColors.push(hslToHex((hslCustom.h + 30) % 360, hslCustom.s, hslCustom.l));
            });
        }
        
        return additionalColors;
    }
    
    // 计算颜色和谐度评分
    function calculateHarmonyScore(colors) {
        if (colors.length <= 1) return 0;
        
        let totalScore = 0;
        let comparisons = 0;
        
        // 计算每对颜色之间的和谐度
        for (let i = 0; i < colors.length; i++) {
            for (let j = i + 1; j < colors.length; j++) {
                const score = calculateColorHarmony(colors[i], colors[j]);
                totalScore += score;
                comparisons++;
            }
        }
        
        // 计算平均分数并转换为0-100的范围
        const averageScore = comparisons > 0 ? totalScore / comparisons : 0;
        return Math.round(averageScore * 100);
    }
    
    // 计算两个颜色之间的和谐度
    function calculateColorHarmony(color1, color2) {
        const hsl1 = hexToHSL(color1);
        const hsl2 = hexToHSL(color2);
        
        // 计算色相差异 (0-180度)
        const hueDiff = Math.min(Math.abs(hsl1.h - hsl2.h), 360 - Math.abs(hsl1.h - hsl2.h));
        
        // 计算饱和度和亮度差异
        const satDiff = Math.abs(hsl1.s - hsl2.s);
        const lightDiff = Math.abs(hsl1.l - hsl2.l);
        
        // 根据色彩理论，某些色相差异更和谐
        // 例如：互补色(180度)，三角色(120度)，类似色(30度)等
        let hueHarmony;
        if (hueDiff < 10) {
            // 几乎相同的色相
            hueHarmony = 0.8;
        } else if (Math.abs(hueDiff - 30) < 10) {
            // 类似色
            hueHarmony = 0.9;
        } else if (Math.abs(hueDiff - 60) < 10) {
            // 类似色变体
            hueHarmony = 0.85;
        } else if (Math.abs(hueDiff - 90) < 10) {
            // 直角色
            hueHarmony = 0.8;
        } else if (Math.abs(hueDiff - 120) < 10) {
            // 三角色
            hueHarmony = 0.9;
        } else if (Math.abs(hueDiff - 150) < 10) {
            // 分裂互补色
            hueHarmony = 0.85;
        } else if (Math.abs(hueDiff - 180) < 10) {
            // 互补色
            hueHarmony = 1.0;
        } else {
            // 其他色相差异
            hueHarmony = 0.7;
        }
        
        // 饱和度和亮度的和谐度 (差异越小越和谐)
        const satHarmony = 1 - (satDiff / 100);
        const lightHarmony = 1 - (lightDiff / 100);
        
        // 综合评分 (给予色相差异更高的权重)
        return (hueHarmony * 0.6) + (satHarmony * 0.2) + (lightHarmony * 0.2);
    }
    
    // 显示结果
    function displayResults(colors, score) {
        // 清空之前的结果
        generatedPalette.innerHTML = '';
        paletteDetails.innerHTML = '';
        
        // 显示生成的颜色
        colors.forEach(color => {
            const colorCard = document.createElement('div');
            colorCard.className = 'color-card';
            colorCard.style.backgroundColor = color;
            colorCard.innerHTML = `<span>${color}</span>`;
            
            // 点击复制颜色代码
            colorCard.addEventListener('click', () => {
                navigator.clipboard.writeText(color)
                    .then(() => showCopyToast(`已复制颜色: ${color}`));
            });
            
            generatedPalette.appendChild(colorCard);
        });
        
        // 显示和谐度评分 (带动画)
        animateCounter(harmonyScore, 0, score, 1500);
        
        // 设置评分条
        setTimeout(() => {
            harmonyScoreBar.style.width = `${score}%`;
            
            // 根据分数设置颜色
            if (score < 50) {
                harmonyScoreBar.style.background = 'linear-gradient(to right, #ff5252, #ff8c00)';
            } else if (score < 75) {
                harmonyScoreBar.style.background = 'linear-gradient(to right, #ff8c00, #ffd700)';
            } else {
                harmonyScoreBar.style.background = 'linear-gradient(to right, #ffd700, #4caf50)';
            }
        }, 100);
        
        // 显示颜色详情
        colors.forEach((color, index) => {
            const hsl = hexToHSL(color);
            const colorName = getColorName(hsl.h, hsl.s, hsl.l);
            
            const colorDetail = document.createElement('div');
            colorDetail.className = 'color-detail';
            colorDetail.innerHTML = `
                <div class="color-swatch" style="background-color: ${color};"></div>
                <div class="color-info">
                    <div class="color-name">${colorName}</div>
                    <div class="color-hex">${color} | HSL(${Math.round(hsl.h)}, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%)</div>
                </div>
            `;
            
            // 延迟添加以创建动画效果
            setTimeout(() => {
                paletteDetails.appendChild(colorDetail);
            }, index * 100);
        });
    }
    
    // 保存配色方案
    function savePalette() {
        // 获取当前生成的颜色
        const colorCards = document.querySelectorAll('.color-card');
        if (colorCards.length === 0) return;
        
        const colors = Array.from(colorCards).map(card => card.style.backgroundColor);
        
        // 创建一个名称
        const date = new Date();
        const paletteName = `配色方案 ${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
        
        // 创建保存对象
        const palette = {
            id: Date.now(),
            name: paletteName,
            colors: colors,
            date: date.toISOString()
        };
        
        // 获取已保存的配色
        let savedPalettes = JSON.parse(localStorage.getItem('colorPalettes')) || [];
        
        // 添加新配色
        savedPalettes.push(palette);
        
        // 保存到本地存储
        localStorage.setItem('colorPalettes', JSON.stringify(savedPalettes));
        
        // 更新显示
        loadSavedPalettes();
        
        // 显示成功消息
        showCopyToast('配色方案已保存');
        
        // 滚动到已保存的配色区域
        document.getElementById('savedPalettes').scrollIntoView({ behavior: 'smooth' });
    }
    
    // 加载已保存的配色方案
    function loadSavedPalettes() {
        savedPalettesContainer.innerHTML = '';
        
        // 获取已保存的配色
        const savedPalettes = JSON.parse(localStorage.getItem('colorPalettes')) || [];
        
        if (savedPalettes.length === 0) {
            savedPalettesContainer.innerHTML = '<p>暂无保存的配色方案</p>';
            return;
        }
        
        // 显示已保存的配色
        savedPalettes.forEach(palette => {
            const paletteElement = document.createElement('div');
            paletteElement.className = 'saved-palette';
            
            // 创建颜色条
            let colorsHTML = '<div class="saved-colors">';
            palette.colors.forEach(color => {
                colorsHTML += `<div class="saved-color" style="background-color: ${color};"></div>`;
            });
            colorsHTML += '</div>';
            
            // 创建信息和操作按钮
            const date = new Date(palette.date);
            paletteElement.innerHTML = `
                ${colorsHTML}
                <div class="saved-palette-info">
                    <div class="saved-palette-name">${palette.name}</div>
                    <div class="saved-palette-date">${date.toLocaleDateString()} ${date.toLocaleTimeString()}</div>
                    <div class="saved-palette-actions">
                        <button class="saved-palette-btn load-btn" data-id="${palette.id}"><i class="fas fa-sync-alt"></i> 加载</button>
                        <button class="saved-palette-btn delete-btn" data-id="${palette.id}"><i class="fas fa-trash"></i> 删除</button>
                    </div>
                </div>
            `;
            
            savedPalettesContainer.appendChild(paletteElement);
        });
        
        // 添加加载和删除按钮的事件
        document.querySelectorAll('.load-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const paletteId = parseInt(this.dataset.id);
                loadPalette(paletteId);
            });
        });
        
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const paletteId = parseInt(this.dataset.id);
                deletePalette(paletteId);
            });
        });
    }
    
    // 加载特定配色方案
    function loadPalette(paletteId) {
        const savedPalettes = JSON.parse(localStorage.getItem('colorPalettes')) || [];
        const palette = savedPalettes.find(p => p.id === paletteId);
        
        if (!palette) return;
        
        // 设置主颜色
        if (palette.colors.length > 0) {
            mainColor.value = rgbToHex(palette.colors[0]);
            mainColorHex.value = mainColor.value;
            mainColorPreview.style.backgroundColor = mainColor.value;
        }
        
        // 清除现有的自定义颜色
        customColorsContainer.innerHTML = '';
        
        // 添加其余颜色作为自定义颜色
        for (let i = 1; i < palette.colors.length; i++) {
            const color = rgbToHex(palette.colors[i]);
            addCustomColorWithValue(color);
        }
        
        // 生成配色方案
        generatePalette();
        
        // 显示成功消息
        showCopyToast('配色方案已加载');
    }
    
    // 添加指定颜色值的自定义颜色
    function addCustomColorWithValue(colorValue) {
        const customColorItem = document.createElement('div');
        customColorItem.className = 'custom-color-item';
        
        customColorItem.innerHTML = `
            <div class="color-picker-container">
                <input type="color" class="customColor" value="${colorValue}">
                <input type="text" class="customColorHex" value="${colorValue}">
            </div>
            <div class="color-preview custom-preview" style="background-color: ${colorValue};"></div>
            <button class="remove-btn"><i class="fas fa-times"></i></button>
        `;
        
        customColorsContainer.appendChild(customColorItem);
        
        // 设置新添加的颜色选择器的事件
        const newColorInput = customColorItem.querySelector('.customColor');
        const newHexInput = customColorItem.querySelector('.customColorHex');
        const newPreview = customColorItem.querySelector('.custom-preview');
        const removeBtn = customColorItem.querySelector('.remove-btn');
        
        setupColorPicker(newColorInput, newHexInput, newPreview);
        
        removeBtn.addEventListener('click', function() {
            customColorItem.remove();
        });
    }
    
    // 删除配色方案
    function deletePalette(paletteId) {
        let savedPalettes = JSON.parse(localStorage.getItem('colorPalettes')) || [];
        savedPalettes = savedPalettes.filter(p => p.id !== paletteId);
        localStorage.setItem('colorPalettes', JSON.stringify(savedPalettes));
        
        // 更新显示
        loadSavedPalettes();
        
        // 显示成功消息
        showCopyToast('配色方案已删除');
    }
    
    // 复制配色代码
    function copyPaletteCode() {
        const colorCards = document.querySelectorAll('.color-card');
        if (colorCards.length === 0) return;
        
        const colors = Array.from(colorCards).map(card => card.style.backgroundColor);
        
        // 创建CSS变量代码
        let cssCode = ':root {\n';
        colors.forEach((color, index) => {
            const hexColor = rgbToHex(color);
            cssCode += `  --color-${index + 1}: ${hexColor};\n`;
        });
        cssCode += '}\n\n';
        
        // 添加示例用法
        cssCode += '/* 示例用法 */\n';
        cssCode += '.primary-bg { background-color: var(--color-1); }\n';
        cssCode += '.accent-bg { background-color: var(--color-2); }\n';
        
        // 复制到剪贴板
        navigator.clipboard.writeText(cssCode)
            .then(() => showCopyToast('CSS代码已复制到剪贴板'));
    }
    
    // 显示复制成功提示
    function showCopyToast(message) {
        // 检查是否已存在toast
        let toast = document.querySelector('.copy-toast');
        
        if (!toast) {
            toast = document.createElement('div');
            toast.className = 'copy-toast';
            document.body.appendChild(toast);
        }
        
        toast.textContent = message;
        toast.classList.add('show');
        
        // 3秒后隐藏
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
    
    // 数字计数器动画
    function animateCounter(element, start, end, duration) {
        let startTime = null;
        
        function animation(currentTime) {
            if (!startTime) startTime = currentTime;
            const timeElapsed = currentTime - startTime;
            const progress = Math.min(timeElapsed / duration, 1);
            const value = Math.floor(progress * (end - start) + start);
            
            element.textContent = value;
            
            if (progress < 1) {
                requestAnimationFrame(animation);
            }
        }
        
        requestAnimationFrame(animation);
    }
    
    // 颜色转换函数
    
    // HEX转HSL
    function hexToHSL(hex) {
        // 移除#号
        hex = hex.replace(/^#/, '');
        
        // 将hex转换为rgb
        let r, g, b;
        if (hex.length === 3) {
            r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
            g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
            b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
        } else {
            r = parseInt(hex.substring(0, 2), 16) / 255;
            g = parseInt(hex.substring(2, 4), 16) / 255;
            b = parseInt(hex.substring(4, 6), 16) / 255;
        }
        
        // 找出最大和最小的RGB值
        const max = Math.max(r, g, b);
        const min = Math.min(r, g, b);
        let h, s, l = (max + min) / 2;
        
        if (max === min) {
            // 灰色
            h = s = 0;
        } else {
            const d = max - min;
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
            
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                case g: h = (b - r) / d + 2; break;
                case b: h = (r - g) / d + 4; break;
            }
            
            h /= 6;
        }
        
        return { h: h * 360, s: s * 100, l: l * 100 };
    }
    
    // HSL转HEX
    function hslToHex(h, s, l) {
        h /= 360;
        s /= 100;
        l /= 100;
        
        let r, g, b;
        
        if (s === 0) {
            r = g = b = l;
        } else {
            const hue2rgb = (p, q, t) => {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1/6) return p + (q - p) * 6 * t;
                if (t < 1/2) return q;
                if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
                return p;
            };
            
            const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            const p = 2 * l - q;
            
            r = hue2rgb(p, q, h + 1/3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1/3);
        }
        
        const toHex = x => {
            const hex = Math.round(x * 255).toString(16);
            return hex.length === 1 ? '0' + hex : hex;
        };
        
        return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
    }
    
    // RGB转HEX
    function rgbToHex(rgb) {
        // 检查是否已经是hex格式
        if (rgb.startsWith('#')) {
            return rgb;
        }
        
        // 从rgb(r, g, b)或rgba(r, g, b, a)格式中提取RGB值
        const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d.]+\s*)?\)/i;
        const match = rgb.match(rgbRegex);
        
        if (!match) return rgb; // 如果不是有效的RGB格式，返回原始值
        
        const r = parseInt(match[1]);
        const g = parseInt(match[2]);
        const b = parseInt(match[3]);
        
        // 转换为hex
        return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
    }
    
    // 获取颜色名称
    function getColorName(h, s, l) {
        // 基于HSL值确定颜色名称
        let name = '';
        
        // 确定色相名称
        if (s < 10) {
            if (l < 20) return '黑色';
            if (l > 80) return '白色';
            return '灰色';
        }
        
        if (h < 30) name = '红色';
        else if (h < 60) name = '橙色';
        else if (h < 90) name = '黄色';
        else if (h < 150) name = '绿色';
        else if (h < 210) name = '青色';
        else if (h < 270) name = '蓝色';
        else if (h < 330) name = '紫色';
        else name = '红色';
        
        // 添加亮度和饱和度描述
        if (s < 40) name = '淡' + name;
        else if (s > 80) name = '深' + name;
        
        if (l < 30) name += '(暗)';
        else if (l > 70) name += '(亮)';
        
        return name;
    }
});